package com.fan.exception;

import com.fan.common.Result;
import com.fan.common.StateCodeEnum;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.UnsupportedCommOperationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理-运行期捕获以下定义的所有异常
 *
 * @Author: fan
 * @DateTime: 2021-06-17 14:27
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Result result = new Result();

    private GlobalExceptionHandler() {}

    @ExceptionHandler(NoSuchPortException.class)
    public Result noSuchPortException(NoSuchPortException e) {
        result.setCode(StateCodeEnum.FAIL.getCode());
        result.setMsg("端口不存在！");
        result.setData(e.getMessage());
        return result;
    }

    @ExceptionHandler(PortInUseException.class)
    public Result noSuchPortException(PortInUseException e) {
        result.setCode(StateCodeEnum.FAIL.getCode());
        result.setMsg("端口被占用！");
        result.setData(e.getMessage());
        return result;
    }

    @ExceptionHandler(UnsupportedCommOperationException.class)
    public Result unsupportedCommOperationException(UnsupportedCommOperationException e) {
        result.setCode(StateCodeEnum.FAIL.getCode());
        result.setMsg("无法获取指定端口！");
        result.setData(e.getMessage());
        return result;
    }
}
